package com.yy.micro.magic.core.provider.impl;

import com.yy.micro.magic.ext.domain.code.CodeMap;
import com.yy.micro.magic.ext.domain.code.CodeMapItem;

import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Optional;
import java.util.Set;

public abstract class CodeMapResourceProvider extends AbstractResourceProvider<Set<CodeMap>>{

    public CodeMapItem findCodeMapItem(String planCode, String codeName, Object value){
        Set<CodeMap> codeMaps = find(planCode);
        if (!CollectionUtils.isEmpty(codeMaps)){
            Optional<CodeMap> map=codeMaps.stream().filter(c->c.match(codeName,value)).findFirst();
            return map.isPresent()?map.get().findCodeItem(value):null;
        }
        return null;
    }

    @Override
    public void regist(final String code, final Set<CodeMap> entity) {
        Set<CodeMap> maps = find(code);
        if (null != maps){
            maps.addAll(entity);
        }else{
            super.regist(code, entity);
        }
    }

    public Object findCodeTargetValue(String planCode, String codeName, Object value){
        CodeMapItem item = findCodeMapItem(planCode,codeName,value);
        return null != item?item.getTargetValue():null;
    }
    @Component("codeImpl")
    public static class Impl extends CodeMapResourceProvider{

    }
}
